package com.cxf.windex.rest;

import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.msg.TableResultResponse;
import com.cxf.windex.base.rest.BaseRestController;
import com.cxf.windex.base.util.IdUtil;
import com.cxf.windex.base.util.WxUtil;
import com.cxf.windex.biz.AddressBiz;
import com.cxf.windex.biz.JsFollowBiz;
import com.cxf.windex.biz.JsTechBiz;
import com.cxf.windex.entity.Address;
import com.cxf.windex.entity.JsFollow;
import com.cxf.windex.entity.JsTech;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenxf
 * @date 3/16/2018
 * @description
 */
@Api(tags = {"小程序 - 技师接口"})
@Controller
@RequestMapping("/user/tech")
public class TechController extends BaseRestController<JsTechBiz, JsTech> {

  @Autowired
  private JsFollowBiz jsFollowBiz;
  @Autowired
  private AddressBiz addresBiz;

  @Value("${weixin.appid}")
  private String appid;

  @Value("${weixin.secret}")
  private String secret;

  /**
   * 文件存放 路径
   */
  @Value("${upload.path}")
  private String uploadPath;

  /**
   * 文件访问路径
   */
  @Value("${upload.url}")
  private String uploadUrl;

  /**
   * 文件访问域名
   */
  @Value("${upload.uri}")
  private String uploadUri;

  @ApiOperation(value = "查询技师列表", notes = "查询技师列表")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "limit", value = "记录数", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "offset", value = "页码", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "orderStr", value = "排序 desc", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "title", value = "名称", required = false, paramType = "query", dataType = "String"),
  })
  @RequestMapping(value = "/list", method = RequestMethod.GET)
  @ResponseBody
  public TableResultResponse<JsTech> list(
          @RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1") int offset,
          @RequestParam(defaultValue = "desc") String orderStr, String title) {
    Example example = new Example(JsTech.class);
    Criteria criteria = example.createCriteria();
    if (StringUtils.isNotBlank(title)) {
      criteria.andLike("title", "%" + title + "%");
    }
    example.setOrderByClause(" crt_time "+orderStr);
    PageHelper.startPage(offset, limit);
    List<JsTech> items=baseBiz.selectByExample(example);
    PageInfo<JsTech> pageInfo = new PageInfo<JsTech>(items);

    return new TableResultResponse<JsTech>(Integer.parseInt(String.valueOf(pageInfo.getTotal())), offset, limit,
        items);

  }

  @ApiOperation(value = "查询技师列表", notes = "查询技师列表")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "limit", value = "记录数", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "offset", value = "页码", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "address", value = "地址", required = true, paramType = "query", dataType = "String"),
  })
  @RequestMapping(value = "/name", method = RequestMethod.GET)
  @ResponseBody
  public TableResultResponse<JsTech> name(
          @RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1") int offset,
          @RequestParam String address) {
    Example example = new Example(JsTech.class);
    Criteria criteria = example.createCriteria();
    if(StringUtils.isNotBlank(address)){
      criteria.andLike("address",address + "%");
    }
    example.setOrderByClause(" score desc");
    int count =0;
        //baseBiz.selectCountByExample(example);
    PageHelper.startPage(offset, limit);
    return new TableResultResponse<JsTech>(count, offset, limit,
        baseBiz.selectByExample(example));

  }

  @ApiOperation(value = "新增/编辑/查看", notes = "新增编辑查看")
  @RequestMapping(value = "/edit", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse edit(JsTech entity) {
    if (StringUtils.isBlank(entity.getId())) {
      return new ObjectRestResponse().rel(true).msg("技师ID不能为空");
    }
    entity = baseBiz.selectById(entity.getId());

    String userId = this.getCurrentUserId();
    if (userId==null) {
      userId="1";
    }

    JsFollow queryEntity = new JsFollow();
    queryEntity.setUserid(userId);
    queryEntity.setTouserid(entity.getId());
    JsFollow follow = jsFollowBiz.selectOne(queryEntity);
    if (follow == null ) {
      entity.setStatus("0");
    }else{
      entity.setStatus("1");
    }
    return new ObjectRestResponse().rel(true).msg("查询成功").result(entity);
  }

  @ApiOperation(value = "支付失败", notes = "支付失败")
  @RequestMapping(value = "/payfail", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse payfail() {
    String userId = this.getCurrentUserId();
    if (userId == null || userId.equals("")) {
      return new ObjectRestResponse().rel(false).msg("用户不存在");
      // userId="426784124636909568";
    }

    JsTech queryEntity = new JsTech();
    queryEntity.setUserid(userId);
    JsTech tech = baseBiz.selectOne(queryEntity);
    if (tech != null) {
      JsTech saveEntity = new JsTech();
      saveEntity.setId(tech.getId());
      saveEntity.setStatus("0");
      saveEntity.setPayStatus("支付失败");
      saveEntity.setUpdTime(new Date());
      baseBiz.updateSelectiveById(saveEntity);
    }
    return new ObjectRestResponse().rel(true).msg("保存成功");
  }

  @CacheEvict(value="addressList",allEntries=true)
  @ApiOperation(value = "保存", notes = "保存")
  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse save(@RequestBody JsTech entity) {
    boolean isAdd=false;
    if(StringUtils.isBlank(entity.getId())){
      isAdd=true;
      entity.setId(new IdUtil(2,1).nextId()+"");
      entity.setFollowers(0);
      entity.setScore(0);
      String userId = this.getCurrentUserId();

      if ( userId==null || userId.equals("") ) {
        return new ObjectRestResponse().rel(false).msg("用户异常");
        // userId="1";
      }
      entity.setUserid(userId);
    }
   if(StringUtils.isNotBlank(entity.getLatitude())&&StringUtils.isNotBlank(entity.getLongitude())){
     /**
      * 设置地图信息
      */
     address(entity,isAdd);
   }
    if(isAdd){
      baseBiz.insertSelective(entity);
    }else{
      baseBiz.updateSelectiveById(entity);
    }
    Map<String,String> resultMap=new HashMap<String,String>(1);
    resultMap.put("jsId",entity.getId());
    return new ObjectRestResponse().rel(true).msg("保存成功").result(resultMap);
  }

  @Override
  @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
  @ResponseBody
  public ObjectRestResponse remove(@PathVariable String id){

    addresBiz.deleteById(id);
     baseBiz.deleteById(id);
    return new ObjectRestResponse().rel(true);
  }
  private void address(JsTech entity,boolean isAdd){
    if(isAdd){
      //addresBiz.insertAddress(new Address(entity));
    }else{
      addresBiz.updateAddressById(new Address(entity));
    }
  }


  @RequestMapping(value = "minaCode",method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse minaCode(@RequestParam(defaultValue = "index")String scene, @RequestParam(defaultValue = "pages/index/index") String page){
    String userId = this.getCurrentUserId();
    Map<String,String> map=new HashMap<>(2);
    if(StringUtils.isNotBlank(scene)){
      scene+="&";
    }
    scene+="userId="+userId;
    map.put("path",page+"?"+scene);
    logger.debug("map={}",map);
    byte[] codeBytes= WxUtil.getMinaCode(appid,secret, map);
    logger.debug(new String(codeBytes));
    String webRoot  = uploadPath  + File.separator  +"mina" + File.separator;
    String saveUrl =uploadUri+ uploadUrl+ "/mina/mina"+userId +".jpg";
    File directoryFile = new File(webRoot);
    if(!directoryFile.exists()) {
      directoryFile.mkdirs();
    }
    Path path = Paths.get(webRoot+"mina"+userId+".jpg");
    try {
      Files.write(path, codeBytes);
      return new ObjectRestResponse().rel(true).result(saveUrl);
    } catch (IOException e) {
      e.printStackTrace();
    }

    return new ObjectRestResponse().rel(false);
  }

}
